<?php

namespace App\Admin\Widgets\Show;

use Dcat\Admin\Show as AdminShow;
use Dcat\Admin\Show\Row;
use Closure;
class Show extends AdminShow
{
    protected $blocks = [];

    public function __construct($id = null, $model = null, ?\Closure $builder = null)
    {
        parent::__construct($id, $model, $builder);
    }

    /**
     * Initialize panel.
     */
    // protected function initPanel()
    // {
    //     $this->panel = new Panel($this);
    // }

    public function blocks($blocks)
    {
        $this->blocks = $blocks;
    }

    /**
     * Add a row in Show.
     *
     * @param  Closure  $callback
     * @return $this
     */
    public function block_row(Closure $callback, $block = [])
    {
        $row = new Row($callback, $this);
        $this->rows->push($row);
        if ($block) {
            $new_blocks = $this->blocks;

            $find = false;
            if (isset($block['title'])) {
                foreach($this->blocks as $key => $current_block) {
                    if (!isset($new_blocks[$key]['rows'])) {
                        $new_blocks[$key]['rows'] = [];
                    }
                    if ($current_block['title'] == $block['title']) {
                        $find = true;
                        array_push($new_blocks[$key]['rows'], $row);
                        break;
                    }
                }
            } else {
                $block['title'] = '基础信息';
            }
            

            if (!$find) {
                array_push($new_blocks, [
                    'title' => $block['title'],
                    'rows' => [$row]
                ]);
            }
            $this->blocks = $new_blocks;
        }
        return $this;
    }

    /**
     * Render the show panels.
     *
     * @return string
     */
    public function render()
    {
        $model = $this->model();

        if (is_callable($this->builder)) {
            call_user_func($this->builder, $this);
        }

        if ($this->fields->isEmpty()) {
            $this->all();
        }

        if (is_array($this->builder)) {
            $this->fields($this->builder);
        }

        $this->fields->each->fill($model);
        $this->relations->each->model($model);

        $this->callComposing();

        $data = [
            'panel'     => $this->panel->fill($this->fields),
            'relations' => $this->relations,
        ];
        $data['panel']->addVariables(['blocks' => $this->blocks]);
        // dd($data['panel']);
        return view($this->view, $data)->render();
    }
}
